package com.reyco1.data
{
	public class DataFormatter
	{
		public static function formatData(dataObject:Object):Array
		{
			var retArr:Array;
			var nodes:XMLList;
			var obj:Object
			var attrs:XMLList
			var node:XML
			var attr:XML
			var propNodes:XMLList
			var propNode:XML
			
			if (dataObject is Array) 
			{
				var arr:Array = dataObject as Array;
				if (arr.length > 0) 
				{
					if (arr[0] is String || arr[0] is Number) 
					{
						retArr = [];
						
						for (var i:uint = 0; i < arr.length; i++) 
						{
							var o:Object = {label:String(arr[i]), data:arr[i]};
							retArr.push(o);
						}
						
						return retArr;
					}
				}
				return dataObject.concat();
			} 
			else if (dataObject is DataProvider) 
			{
				return dataObject.toArray();
			} 
			else if (dataObject is XML) 
			{
				var xml:XML = dataObject as XML;
				retArr = [];
				
				nodes = xml.*;
				for each (node in nodes) 
				{
					dataObject = {};
					attrs = node.attributes();
					for each (attr in attrs) 
					{
						dataObject[attr.localName()] = attr.toString();
					}
					
					propNodes = node.*;
					for each (propNode in propNodes) 
					{
						if (propNode.hasSimpleContent()) 
						{
							dataObject[propNode.localName()] = propNode.toString();
						}
					}
					
					retArr.push(dataObject);
				}
				return retArr;
			} 
			else if (dataObject is XMLList)
			{
				retArr = [];
				
				nodes = dataObject as XMLList;
				for each (node in nodes) 
				{
					dataObject = {};
					attrs = node.attributes();
					for each (attr in attrs) 
					{
						dataObject[attr.localName()] = attr.toString();
					}
					
					propNodes = node.*;
					for each (propNode in propNodes) 
					{
						if (propNode.hasSimpleContent()) 
						{
							dataObject["nodeValue"] = propNode.toString(); //propNode.localName()
						}
					}
					
					retArr.push(dataObject);
				}
				return retArr;
			}
			else 
			{
				throw new Error("Error: Type Coercion failed: cannot convert " + dataObject + " to Array or Dataprovider.");
				return null;
			}
		}
	}
}